//
//  ViewController.swift
//  5SwiftWeather
//
//  Created by 杜承玖 on 2/9/15.
//  Copyright (c) 2015 redianying. All rights reserved.
//

import UIKit
import CoreLocation

class ViewController: UIViewController,
 CLLocationManagerDelegate {
    
    let locationManger:CLLocationManager = CLLocationManager()

    @IBOutlet var location: UILabel!
    @IBOutlet var icon: UIImageView!
    @IBOutlet var termperature: UILabel!
    @IBOutlet var loadingIndicator: UIActivityIndicatorView!
    @IBOutlet var loading: UILabel!
    
    //temperature
    override func viewDidLoad() {
        super.viewDidLoad()
        
        locationManger.delegate = self;
        locationManger.desiredAccuracy = kCLLocationAccuracyBest
        
        self.loadingIndicator.startAnimating()
        
        let background = UIImage(named: "background.png")
        self.view.backgroundColor = UIColor(patternImage:background!)
        
        if (ios8()) {//针对ios8, 需要设置一个参数
            locationManger.requestAlwaysAuthorization()
        }
        locationManger.startUpdatingLocation()
    }
    
    func ios8() -> Bool {
        //这里只做简单的示例, 做真正的程序应该把前面的版本号取出来比较
        return UIDevice.currentDevice().systemVersion >= "8.0"
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //当位置发生变化时的回调函数
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        var location : CLLocation = locations[locations.count-1] as CLLocation //将最后一个位置信息对象取出来
        
        if location.horizontalAccuracy > 0 {
            println(location.coordinate.latitude)
            println(location.coordinate.longitude)
            //调用更新天气信息
            updateWeatherInfo(location.coordinate.latitude, longitude: location.coordinate.longitude)
            locationManger.stopUpdatingLocation() //一旦获取到了之后就停止
        }
    }
    
    func updateWeatherInfo(latitude: CLLocationDegrees, longitude:CLLocationDegrees) {
        
        let manager = AFHTTPRequestOperationManager()
        let url = "http://api.openweathermap.org/data/2.5/weather"
        
        let params = ["lat":latitude, "lon":longitude, "cnt":0]
        
        manager.GET(url,
            parameters: params,
            success: { (operation: AFHTTPRequestOperation!,
                responseObject: AnyObject!) in
                println("JSON: " + responseObject.description!)
                
                self.updateUISuccess(responseObject as NSDictionary!)
            },
            failure: { (operation: AFHTTPRequestOperation!,
                error: NSError!) in
                println("Error: " + error.localizedDescription)
        })
        
    }
    
    func updateUISuccess(jsonResult:NSDictionary!) {
        self.loadingIndicator.stopAnimating()
        self.loading.text = nil
        
        if let tempResult = jsonResult["main"]?["temp"]? as? Double {
            //设置温度
            var temperature:Double
            if (jsonResult["sys"]?["country"]? as String == "US") {
                temperature = round(((tempResult - 273.15) * 1.8) + 32)
            } else {
                temperature = round(tempResult - 273.15)
            }
            self.termperature.text = "\(temperature)°"
            
            var name = jsonResult["name"]? as String
            self.location.text = "\(name)"
            
            var condition = (jsonResult["weather"]? as NSArray)[0]["id"]? as Int
            //由于有白天和黑夜, 所以要获取日出和日落的信息
            var sunrise = jsonResult["sys"]?["sunrise"]? as Double
            var sunset = jsonResult["sys"]?["sunset"]? as Double
            
            var nightTime = false
            var now = NSDate().timeIntervalSince1970
            
            if (now < sunrise || now > sunset) {
                nightTime = true
            }
            
            //更新天气图标
            self.updateWeatherIcon(condition, nightTime:nightTime)
        }
        else {
            self.loading.text = "天气信息不可用"
        }
    }
    
    func updateWeatherIcon(condition: Int, nightTime:Bool) {
        if (condition < 300) {
            if nightTime {
                self.icon.image = UIImage(named: "tstorm1_night")
            } else {
                self.icon.image = UIImage(named: "tstorm1")
            }
        } else if (condition < 500) {
            if nightTime {
                self.icon.image = UIImage(named: "light_rain")
            } else {
                self.icon.image = UIImage(named: "light_rain")
            }
            
        } else if (condition < 600) {
            if nightTime {
                self.icon.image = UIImage(named: "shower3")
            } else {
                self.icon.image = UIImage(named: "shower3")
            }
        } else if (condition < 700) {
            if nightTime {
                self.icon.image = UIImage(named: "snow4")
            } else {
                self.icon.image = UIImage(named: "snow4")
            }
        } else if (condition < 771) {
            if nightTime {
                self.icon.image = UIImage(named: "fog_night")
            } else {
                self.icon.image = UIImage(named: "fog")
            }
        } else if (condition < 800) {
                self.icon.image = UIImage(named: "tstorm3")
        } else if (condition == 800) {
            if nightTime {
                self.icon.image = UIImage(named: "sunny_night")
            } else {
                self.icon.image = UIImage(named: "sunny")
            }
        } else if (condition < 804) {
            if nightTime {
                self.icon.image = UIImage(named: "cloudy_night")
            } else {
                self.icon.image = UIImage(named: "cloudy2")
            }
        } else if (condition == 804) {
                self.icon.image = UIImage(named: "overcast")
        } else if ( (condition >= 900 && condition<903) || (condition>904 && condition<1000) ) {
                self.icon.image = UIImage(named: "tstorm3")
        } else if (condition == 903) {
                self.icon.image = UIImage(named: "snow5")
        } else if (condition == 904) {
                self.icon.image = UIImage(named: "sunny")
        }
    }
    
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        println(error)
        self.loading.text = "地理位置信息不可用"
    }


}

